$dowload_url = "https://gitee.com/ineo6/hosts/raw/master/hosts" # 下载地址
$download_hosts_path = "$HOME\hosts"                            # hosts 下载路径
$hosts_path = "C:\windows\system32\drivers\etc\hosts"           # 系统 hosts 保存路径
$hosts_path_bak = "C:\windows\system32\drivers\etc\hosts.bak"   # 系统 hosts 备份路径
$command = $MyInvocation.MyCommand.Definition                   # powershell 脚本路径

# 判断用户是否为管理员
function is_admin
{
    $user = [Security.Principal.WindowsIdentity]::GetCurrent()
    return (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

# 下载 hosts
function download_hosts 
{
    Write-Host "########## downloading github hosts to $download_hosts_path ##########"
    $client = new-object System.Net.WebClient
    $client.DownloadFile($dowload_url, $download_hosts_path) 
}

# 备份 hosts
function backups_hosts 
{
    Write-Host "########## copying $hosts_path to $hosts_path_bak ##########"
    $original_hosts = Get-Content $hosts_path -Raw
    Set-Content $hosts_path_bak $original_hosts
}

# 删除 hosts 中原有 github 相关配置
function remove_hosts 
{
    Write-Host "########## removing github hosts in $hosts_path ##########"
    $original_hosts = Get-Content $hosts_path -Raw
    $original_hosts = $original_hosts -replace "# GitHub Host Start[\s\S]*?# GitHub Host End", ""
    $original_hosts = ($original_hosts -replace "(?m)^\s*`r`n", "").trim()
    Set-Content $hosts_path $original_hosts
}

# 更新 hosts
function update_hosts 
{
    Write-Host "########## updating github hosts in $hosts_path ##########"
    $new_hosts = Get-Content $download_hosts_path -Raw
    $new_hosts = $new_hosts -replace "#.*", ""
    $new_hosts = ($new_hosts -replace "(?m)^\s*`r`n", "").trim()
    $new_hosts = "", "# GitHub Host Start", $new_hosts, "# GitHub Host End" -join "`n"
    Add-Content $hosts_path $new_hosts
}

# 刷新 DNS
function flush_dns 
{
    Write-Host "########## refreshing DNS ##########"
    ipconfig /flushdns
}

$is_admin = is_admin

# 非管理员则利用 Start-Process 命令来获取管理员权限
if (!$is_admin) 
{
    if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
        Start-Process -FilePath PowerShell.exe -Verb RunAs -ArgumentList $command
        exit
    }
}

download_hosts
backups_hosts
remove_hosts
update_hosts
flush_dns